//
//  SampuxLoginView.m
//  Sampux
//
//  Created by rzm on 16/7/4.
//  Copyright © 2016年 rzm. All rights reserved.
//

#import "SampuxLoginView.h"
#import "IsValidateOrNot.h"
#import "PooCodeView.h"
#import "SPUserBaseMessageModel.h"


#define UserKEY @"UserKEY"

@interface SampuxLoginView ()<UITextFieldDelegate>

@property (nonatomic, strong) UIView *loginView;
@property (nonatomic, strong) PooCodeView *pooCodeView;

//@property (nonatomic, strong) UITextField *phoneF;
//@property (nonatomic, strong) UITextField *passwordF;
@property (nonatomic, strong) UIButton *forgetBtn;
@property (nonatomic, strong) UIButton *keepPasswordBtn;

@property (nonatomic, strong) UITextField *checkCodeTextField;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UIButton *registerBtn;
@property (nonatomic, strong) SPUserBaseMessageModel *userModel;

@property (nonatomic, assign , getter=needSaveUser) BOOL saveUser;
@property (nonatomic, assign)  BOOL isRember;
@property (nonatomic, assign)  BOOL isConnectOrNot;
@property (nonatomic, strong) UILabel *publicLabel;

@end
@implementation SampuxLoginView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestLogin:) name:NOTIFICATION_RESPONSE_LOGIN object:nil];
        self.isConnectOrNot = YES;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(connectFail) name:@"socketConnectFail" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:@"socketConnectSuccess" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getTeleFromRegister:) name:@"remeberTeleWithExist" object:nil];

        [self  setupSubView];

    }
    return self;
}

- (void)connectFail
{
    self.isConnectOrNot = NO;
}
//
- (void)connectSuccess
{
    self.isConnectOrNot = YES;
}

- (void)setupSubView
{
    CGFloat font;
    if (IS_IPHONE_4_OR_LESS) {
        font = 14.;
    }else if (IS_IPHONE_5_OR_LESS)
    {
        font = 14.;
    }else if (IS_IPHONE_6)
    {
        font = 16.;
    }else
    {
        font = 17.;
    }
  
    UIView *loginView = [[UIView alloc] initWithFrame:self.bounds];
    [loginView setCorner:10];
    [self addSubview:loginView];
    CGFloat THCustomSpaceX = self.width/2 - Sampux6WScale(SampuxCustomW)/2;
    self.loginView = loginView;
    
    UIButton *iconImageView = [UIButton createButton];
    [iconImageView setImage:[UIImage imageNamed:@"sampux_logo"] forState:UIControlStateNormal];
    iconImageView.frame = CGRectMake(THCustomSpaceX , Sampux6HScale(115), Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH));
    [self addSubview:iconImageView];
    iconImageView.userInteractionEnabled = NO;

    CGRect phoneRect = CGRectMake(THCustomSpaceX , Sampux6HScale(198), Sampux6WScale(SampuxCustomW),  Sampux6HScale(SampuxCustomH));
    _phoneView = [[SPDeleteTextFiledView alloc]initWithFrame:phoneRect];
    [_phoneView createDeleteTextFiledWithPlaceholder:@"输入手机号" andLeftImage:@"make-user" andRightImage:@"delete"];
    [loginView addSubview:_phoneView];
    _phoneView.textFiled.delegate = self;
//    _phoneF = [UITextField createTextFieldWithRect:phoneRect andPlaceholder:@"请输入手机号或邮箱" andLeftImage:@"user"];
//    _phoneF.delegate = self;
//    self.phoneF = _phoneF;
//    [loginView addSubview:_phoneF];
//    [UIView createLineViewInbottom:_phoneF];

    CGRect passwordRect = CGRectMake(THCustomSpaceX, CGRectGetMaxY(_phoneView.frame) + SampuxMargin,  Sampux6WScale(SampuxCustomW), Sampux6HScale(SampuxCustomH));
//    _passwordF = [UITextField createTextFieldWithRect:passwordRect andPlaceholder:@"请输入密码" andLeftImage:@"password"];
//    _passwordF.delegate = self;
//    [loginView addSubview:_passwordF];
    
    
    _passWordView = [[SampuxCustomTextFiledView alloc]initWithFrame:passwordRect];
    [_passWordView createUserTextFiledWithPlaceholder:@"输入密码" andLeftImage:@"lock" andRightImage:@"eye"];
    _passWordView.textFiled.secureTextEntry = YES;
    _passWordView.textFiled.delegate = self;
//    _passWordView.textFiled.text = @"221412rzm";
    [loginView addSubview:_passWordView];
    _passWordView.warnBtn.hidden = YES;

    _checkCodeTextField = [[UITextField alloc]initWithFrame:CGRectMake(_passWordView.x, CGRectGetMaxY(_passWordView.frame), 0, 0)];
    [loginView addSubview:_checkCodeTextField];
    _checkCodeTextField.placeholder = @"请输入校验码";
    _checkCodeTextField.font = [UIFont systemFontOfSize:font - 1];
    _checkCodeTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _checkCodeTextField.returnKeyType = UIReturnKeyDone;
    _checkCodeTextField.backgroundColor = [UIColor colorWithHex:0xff000000];
    _checkCodeTextField.textColor = THWhiteAlplaColor(0.6);
    [_checkCodeTextField setValue:THWhiteAlplaColor(0.36) forKeyPath:@"_placeholderLabel.textColor"];
    _checkCodeTextField.backgroundColor = THSystemClearColor;
    _checkCodeTextField.delegate = self;
    
    _pooCodeView = [[PooCodeView alloc]initWithFrame:CGRectMake(_passWordView.right - 100, CGRectGetMaxY(_passWordView.frame), 0, 0)];
    [loginView addSubview:_pooCodeView];
    
    _forgetBtn = [UIButton createButtonWithTitle:@"忘记密码" titleFont:[UIFont systemFontOfSize:font - 1] titleColor:THDeFaultBlueColor];
//    _forgetBtn = [UIButton createButtonWithTitle:@"忘记密码" frame:CGRectMake(_passWordView.x  ,CGRectGetMaxY(_checkCodeTextField.frame) + SampuxMargin, 60,loginView.height*0.05) titleFont:[UIFont systemFontOfSize:font - 2] titleColor:THDeFaultBlueColor];
    [_forgetBtn addTarget:self action:@selector(forgetBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [loginView addSubview:_forgetBtn];
    _forgetBtn.contentMode = UIViewContentModeRight;
    _forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _forgetBtn.titleLabel.font = THFont(font - 1);

    _keepPasswordBtn = [UIButton createButton];
//    _keepPasswordBtn.frame = CGRectMake(_passWordView.right - 80, _forgetBtn.y + SampuxMargin ,80, loginView.height*0.05);
    [_keepPasswordBtn setTitleColor:THWhiteAlplaColor(0.6) forState:UIControlStateNormal];
    [_keepPasswordBtn setTitle:@"记住密码" forState:UIControlStateNormal];
    _keepPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:font - 1];
    _keepPasswordBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 5);
    _keepPasswordBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_keepPasswordBtn addTarget:self action:@selector(stateBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_keepPasswordBtn setImage:imageNamed(@"stateBtn_normal") forState:UIControlStateNormal];
    [_keepPasswordBtn setImage:imageNamed(@"stateBtn_selected") forState:UIControlStateSelected];
    [loginView addSubview:_keepPasswordBtn];

    _loginBtn = [UIButton createButtonWithTitle:@"登录" titleFont:[UIFont systemFontOfSize:font] titleColor:THCodeBlueColor];
    _loginBtn.size = CGSizeMake(Sampux6WScale(354/2), Sampux6HScale(45));
    [_loginBtn setCorner:_loginBtn.height/2];
    _loginBtn.backgroundColor = THSystemClearColor;
    [loginView addSubview:_loginBtn];
    _loginBtn.layer.borderWidth = 1;
    _loginBtn.layer.borderColor = THSystemWhiteColor.CGColor;
    [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    _registerBtn = [UIButton createButtonWithTitle:@"新用户注册" titleFont:[UIFont systemFontOfSize: font] titleColor:THCodeBlueColor];
    _registerBtn.size = CGSizeMake(Sampux6WScale(354/2), Sampux6HScale(45));
    [loginView addSubview:_registerBtn];
    [_registerBtn setCorner:_loginBtn.height/2];
    [_registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    _registerBtn.layer.borderWidth = 1;
    _registerBtn.layer.borderColor = THSystemWhiteColor.CGColor;
    _registerBtn.backgroundColor = THSystemClearColor;

    _isRember = [SPUserBaseMessageModel getIsRememberUserPassWordOrNOt];
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:[self getUserIDic]];

//    if (_isRember) {
        __weak typeof(SampuxLoginView *) wSelf = self;
    
        if (array.count) {
            [array enumerateObjectsUsingBlock:^(SPUserBaseMessageModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.isCurrentAccount) {
                    _userModel = obj;
                    *stop = YES;
                }
            }];
        }
        _phoneView.textFiled.text = STRING_FORMAT(self.userModel.phoneStr);
        _passWordView.textFiled.text = STRING_FORMAT(self.userModel.passWordStr) ;
        self.keepPasswordBtn.selected = _isRember;

//    }
//    [self getStateData];
    
    _publicLabel = [UILabel createLabel];
    [loginView addSubview:_publicLabel];
    _publicLabel.text = [NSString stringWithFormat:@"Sampux %@",[SampuxGlobalTool getApplicationVersionCode]];
    _publicLabel.font = THFont(font);
    _publicLabel.textColor = THWhiteAlplaColor(0.6);
    _publicLabel.textAlignment = NSTextAlignmentCenter;
}

- (void)getStateData
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:_phoneView.textFiled.text] !=nil) {
        self.keepPasswordBtn.selected = YES;
        _passWordView.textFiled.text = [[NSUserDefaults standardUserDefaults] objectForKey:_phoneView.textFiled.text];
    }else
    {
        self.keepPasswordBtn.selected = NO;
    }
}

- (void)stateBtnClick
{
    self.keepPasswordBtn.selected = !self.keepPasswordBtn.selected;
    self.isRember = self.keepPasswordBtn.selected;
}

- (void)loginBtnClick
{
    BOOL isMobile  = [IsValidateOrNot isValidateMobile:self.phoneView.textFiled.text];
    BOOL isEmail  = [IsValidateOrNot isValidateEmail:self.phoneView.textFiled.text];
    BOOL isPassword = [IsValidateOrNot isValidatePassword:self.passWordView.textFiled.text];
    
    if ([self.phoneView.textFiled.text isEqualToString:@""] || self.phoneView.textFiled.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"用户名必须为手机号"];
//        [MBProgressHUD showError:@"用户名必须为手机号或者邮箱"];
    }else
    {
        if (!isMobile&&!isEmail)
        {
            [SVProgressHUD showErrorWithStatus:@"用户名错误"];
//            [MBProgressHUD showError:@"用户名错误"];
        }else
        {
            if ([self.passWordView.textFiled.text isEqualToString: @""]|| self.passWordView.textFiled.text.length == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"密码必须为7~16位长度的字母，数字，下划线"];
//                [MBProgressHUD showError:@"密码必须为7~16位长度的字母，数字，下划线"];
            }else
            {
                if (!isPassword) {
                    [SVProgressHUD showErrorWithStatus:@"密码错误"];
//                    [MBProgressHUD showError:@"密码错误"];
                }else
                {
                    if (self.isConnectOrNot == NO) {
                        [SVProgressHUD showErrorWithStatus:@"网络未连接，请检查您的网络连接设置"];
                    }else
                    {
                        [GBInterMaster_CommForSystem requestUserLogin:0 withAccount:_phoneView.textFiled.text withPassword:_passWordView.textFiled.text withCheckCode:_checkCodeTextField.text];
                    [SVProgressHUD showWithStatus:@"正在登录"];
//                        [MBProgressHUD showMessage:@"正在登录"];
                    }
                }
            }
        }
    }
}

- (void)forgetBtnClick
{
    if (self.btnClickDelegate &&[self.btnClickDelegate respondsToSelector:@selector(clickforgetPasswordBtn)])
    {
        [self.btnClickDelegate clickforgetPasswordBtn];
    }
}

- (void)registerBtnClick
{
    if (self.btnClickDelegate &&[self.btnClickDelegate respondsToSelector:@selector(clickRegisterBtn)])
    {
        [self.btnClickDelegate clickRegisterBtn];
    }
}

- (void)requestLogin:(NSNotification* )notification
{
    [SVProgressHUD dismiss];

//    [MBProgressHUD hideHUD];
    id userInfo = [notification userInfo];
    if(userInfo == nil){
        return;
    }
    NSDictionary * result = userInfo;
    int msgNumber = [[result objectForKey:@"msgNumber"] intValue];
    int responseCode = [[result objectForKey:@"responseCode"] intValue];
    NSLog(@"requestLogin == 结果，消息序号：%d，响应码：%x",msgNumber,responseCode);
    if(responseCode == 0x00) {
//        [SVProgressHUD showSuccessWithStatus:@"登录成功"];
//        [MBProgressHUD showError:@"登录成功"];
        if (!self.userModel) {
            _userModel = [[SPUserBaseMessageModel alloc]init];
        }
        self.userModel.phoneStr = _phoneView.textFiled.text;
        self.userModel.passWordStr = _passWordView.textFiled.text;
        
        [SPUserBaseMessageModel saveRememberUserPassWordOrNOt:self.isRember];
            self.userModel.isCurrentAccount = YES;
        NSMutableArray *array = [NSMutableArray arrayWithArray:[self getUserIDic]];
        NSMutableArray *newArray = [NSMutableArray array];
            if (array.count) {
                __block BOOL hadSave = NO;
                [array enumerateObjectsUsingBlock:^(SPUserBaseMessageModel *obj, NSUInteger idx, BOOL * _Nonnull stop)
                 {
                     obj.isCurrentAccount = NO;
                     if ([obj.phoneStr isEqualToString:self.userModel.phoneStr]) {
                         if (!self.isRember) {
                             self.userModel.passWordStr = @"";
                         }
                         self.userModel.isCurrentAccount = YES;
                         obj = self.userModel;
                         hadSave = YES;
                         *stop = YES;
                         NSLog(@"一致");
                    }
                     [newArray addObject:obj];
                 }];
                if (!hadSave) {
                    if (!self.isRember) {
                        self.userModel.passWordStr = @"";
                    }
                    [newArray addObject:self.userModel];
                }
            } else {
                if (!self.isRember) {
                    self.userModel.passWordStr = @"";
                }
                [newArray addObject:self.userModel];
            }
        [self saveUserMessageWithDic:newArray];
        
        if (self.btnClickDelegate &&[self.btnClickDelegate respondsToSelector:@selector(clickLoginBtn)])
        {
            [self.btnClickDelegate clickLoginBtn];
        }
    }else
    {
        [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];

            if ([[result objectForKey:@"isCheck"]integerValue] == 0x00 ) {
                [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];

    //        [MBProgressHUD showError:[SPResponseCodePrompt responseCodePrompt:responseCode]];
            } else {
                dispatch_async(dispatch_get_main_queue(), ^{
                NSString *checkCode = [result objectForKey:@"checkCode"];
                _checkCodeTextField.frame = CGRectMake(_passWordView.x, CGRectGetMaxY(_passWordView.frame) + SampuxMargin, Sampux6WScale(100), Sampux6HScale(SampuxCustomH));
                _pooCodeView.frame = CGRectMake(_passWordView.right - Sampux6WScale(100), CGRectGetMaxY(_passWordView.frame) + SampuxMargin, Sampux6WScale(100), Sampux6HScale(SampuxCustomH));
                _pooCodeView.changeString = checkCode;
                [UIView createLineViewInbottom:_checkCodeTextField];
                [self setNeedsLayout];
                [SVProgressHUD showErrorWithStatus:[SPResponseCodePrompt responseCodePrompt:responseCode]];
    //            [MBProgressHUD showError:[SPResponseCodePrompt responseCodePrompt:responseCode]];
                });
            }
            if (self.userModel) {
                self.userModel.passWordStr = @"";
            }

    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    _forgetBtn.frame = CGRectMake(_passWordView.x  ,CGRectGetMaxY(_checkCodeTextField.frame) + SampuxMargin, Sampux6WScale(80),self.loginView.height*0.05);
    _keepPasswordBtn.frame = CGRectMake(_passWordView.right - 100, _forgetBtn.y ,100, self.loginView.height*0.05);
    _loginBtn.origin = CGPointMake(self.width/2 - Sampux6WScale(354/2)/2, CGRectGetMaxY(_forgetBtn.frame) + self.loginView.height*0.03);
//    _registerBtn.origin = CGPointMake(self.width/2 - 40,CGRectGetMaxY(_loginBtn.frame) + SampuxMargin);
    _registerBtn.origin = CGPointMake(self.width/2 - Sampux6WScale(354/2)/2,CGRectGetMaxY(_loginBtn.frame) + SampuxMargin *2);
    _publicLabel.frame = CGRectMake(self.width/2 - Sampux6WScale(60), _registerBtn.bottom + 30, Sampux6WScale(120), 40) ;
}

- (void)saveUserMessageWithDic:(NSArray *)userArray
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *tokenObject = [NSKeyedArchiver archivedDataWithRootObject:userArray];
    [userDefaults setObject:tokenObject forKey:UserKEY];
    [userDefaults synchronize];
}

- (NSMutableArray *)getUserIDic
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:UserKEY];
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return array;
}

- (void)getTeleFromRegister:(NSNotification *)notification
{
    self.phoneView.textFiled.text = notification.object;
}
#pragma mark UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _checkCodeTextField) {
        NSString * toBeString = [_checkCodeTextField.text stringByReplacingCharactersInRange:range withString:string];
        if (toBeString.length > 6 && range.length!=1){
            textField.text = [toBeString substringToIndex:6];
            return NO;
        }
        return YES;
    } else if (textField == self.passWordView.textFiled){
        NSString * toBeString = [self.passWordView.textFiled.text stringByReplacingCharactersInRange:range withString:string];

        if (toBeString.length > 16 && range.length < 7){
            textField.text = [toBeString substringToIndex:16];
            return NO;
        }
        return YES;
    }else
    {        return YES;
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight );
    return YES;
}
//#pragma -mark 输入框代理
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    CGFloat keyboardHeight = 216.0f;
    self.frame = CGRectMake(0, -40 , kScreenWidth, kScreenHeight);
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self layoutIfNeeded];
    self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.frame = CGRectMake(0, 0 , kScreenWidth, kScreenHeight);
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
